﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Resources;
using System.Windows.Shapes;
using System.Xml.Serialization;
using Microsoft.Phone.BackgroundAudio;
using Microsoft.Phone.Controls;

namespace SimplePlayer
{
    public partial class MainPage : PhoneApplicationPage
    {
        //playlist include paths
        private List<string> playlist;

        // Constructor
        public MainPage()
        {
            CopyToIsolatedStorage("playlist.xml", "playlist.xml");
            LoadPlaylist();
            LoadMusicFiles();
            InitializeComponent();
            PlayListBox.ItemsSource = playlist;

            BackgroundAudioPlayer.Instance.PlayStateChanged += Instance_PlayStateChanged;
        }

        void Instance_PlayStateChanged(object sender, EventArgs e)
        {

            switch (BackgroundAudioPlayer.Instance.PlayerState)
            {
                case PlayState.Playing:
                    PlayButton.Content = "pause";
                    PlayListBox.SelectedItem = BackgroundAudioPlayer.Instance.Track.Source.OriginalString;
                    break;
                case PlayState.Paused:
                case PlayState.Stopped:
                    PlayButton.Content = "play";
                    break;
            }
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            switch (BackgroundAudioPlayer.Instance.PlayerState)
            {
                case PlayState.Playing:
                    PlayButton.Content = "pause";
                    PlayListBox.SelectedItem = BackgroundAudioPlayer.Instance.Track.Source.OriginalString;
                    break;
                case PlayState.Paused:
                case PlayState.Stopped:
                    PlayButton.Content = "play";
                    break;
            }
            base.OnNavigatedTo(e);
        }

        private void CopyToIsolatedStorage(string fullFilePath, string storeFileName)
        {
            using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (!storage.FileExists(storeFileName))
                {

                    StreamResourceInfo resource = Application.GetResourceStream(new Uri(fullFilePath, UriKind.Relative));

                    using (IsolatedStorageFileStream file = storage.CreateFile(storeFileName))
                    {
                        const int chunkSize = 4096;
                        byte[] bytes = new byte[chunkSize];
                        int byteCount;

                        while ((byteCount = resource.Stream.Read(bytes, 0, chunkSize)) > 0)
                        {
                            file.Write(bytes, 0, byteCount);
                        }
                    }
                }
            }
        }
    
        private void LoadPlaylist()
        {
            using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (IsolatedStorageFileStream stream = myIsolatedStorage.OpenFile("playlist.xml", FileMode.Open))
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(List<string>));
                    playlist = (List<string>)serializer.Deserialize(stream);
                }
            }
        }
    
        private void LoadMusicFiles()
        {
            foreach (var filepath in playlist)
            {
                CopyToIsolatedStorage(filepath, filepath);
            }
        }

        private void PlayListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            string filepath = (string)e.AddedItems[0];
                BackgroundAudioPlayer.Instance.Track = new AudioTrack(new Uri(filepath,UriKind.Relative),null,null,null,null);
                BackgroundAudioPlayer.Instance.Play();
        }


        private void PrevButton_Click(object sender, RoutedEventArgs e)
        {
            BackgroundAudioPlayer.Instance.SkipPrevious();

        }

        private void PlayButton_Click(object sender, RoutedEventArgs e)
        {
            if (BackgroundAudioPlayer.Instance.PlayerState == PlayState.Playing)
                BackgroundAudioPlayer.Instance.Pause();
            else BackgroundAudioPlayer.Instance.Play();
        }

        private void NextButton_Click(object sender, RoutedEventArgs e)
        {
            BackgroundAudioPlayer.Instance.SkipNext();

        }
    }
}